package com.jackstraw.tools.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 所在包：com.jackstraw.tools.utils
 * 文件名：
 * 项目：tools
 * 功能描述：
 * 修改人：Xlz
 * 修改时间：2020-08-03 14:56
 */
public class PythonUtil {

    /**
     * 执行python脚本
     * @param scriptName 脚本名称
     * @param argv 脚本运行参数
     * @return
     */
    public static List<String> executePythonScript(String scriptName, String... argv) {
        String[] executeParams = new String[argv.length + 2];
        executeParams[0] = "python";
        executeParams[1] = scriptName;
        for (int i = 0; i < argv.length; i++) {
            executeParams[i+2] = argv[i];
        }
        List<String> result = executePythonScript(executeParams);
        return result;
    }

    /**
     * 执行python脚本
     * @param scriptName 脚本名称
     * @param argv  脚本执行的参数
     * @return
     */
    public static List<String> executePythonScript(String scriptName, List<String> argv) {
        String[] executeParams = new String[argv.size() + 2];
        executeParams[0] = "python";
        executeParams[1] = scriptName;
        for (int i = 0; i < argv.size(); i++) {
            executeParams[i+2] = argv.get(i);
        }
        List<String> result = executePythonScript(executeParams);
        return result;
    }

    /**
     * 执行python脚本， 数组中的第一个参数为脚本名称
     * @param argv
     * @return
     */
    public static List<String> executePythonScript(String[] argv) {
        List<String> result = new ArrayList<>();
        try {
            Process process = Runtime.getRuntime().exec(argv);
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(),"GBK"));
            String line = null;
            while ((line = in.readLine()) != null) {
                result.add(line);
            }
            in.close();
            //java代码中的process.waitFor()返回值为0表示我们调用python脚本成功，
            //返回值为1表示调用python脚本失败，这和我们通常意义上见到的0与1定义正好相反
            int re = process.waitFor();
            if (re != 0) {
                throw new RuntimeException("脚本执行时报错！脚本名称：" + argv[0] + "。脚本全参数：" + argv.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        /*
            # argv.py - 该python脚本仅供测试
            import sys

            for index, param in enumerate(sys.argv):
                if index > 0:
                    print(param)
        */

        String[] argv = new String[]{"Hi man!", "Hello People!"};
        List<String> result = executePythonScript("E://workspace/python/argv.py",  argv);
        System.out.println(result);
    }
}
